console.log(`
  _____   _____   _____  
 /  ___| |  _  \\ |_   _| 
 | |     | |_| |   | |   
 | |  _  |  ___/   | |   
 | |_| | | |       | |   
 \\_____/ |_|       |_|   `);
global.env = process.env.NODE_ENV;

global.API_URI_PREFIX = ""
// API 基础路径
global.API_BASE_PATH = "http://openapi.inventorzxm.com" 
//global.API_BASE_PATH = "http://gptapi.xcx0592.com" 

// 开发环境配置
if(global.env == 'development'){
	//global.API_BASE_PATH = "http://localhost:8081" + global.API_URI_PREFIX 
}
global.API_VERSION = "";

// #ifdef H5
//global.DEBUG_USERID = '4'
// #endif

global.isApp = false;
global.isH5 = false;
global.isMp = false;
// #ifdef APP-PLUS
global.isApp = true;
// #endif
// #ifdef H5
global.isH5 = true;
// #endif
// #ifdef MP
global.isMp = true;
// #endif



// 应用ID
global.APP_ID = 'gpt';


// 应用名称
global.APP_NAME = "GPT"

// 应用标题
global.APP_TITLE = "超乎想象AI"

// 加密秘钥
global.APP_SECRET_KEY = "mz56TI6JvvIkf4Wy"

// AES IV
global.APP_AES_IV = "m4fyvvIkWTI56J6z";

// 分页大小
global.PAGE_SIZE = 20

//主题颜色
global.PRIMARY_COLOR = '#86DFBA';

// 取消
global.CANCEL_COLOR = '#999999';

// 默认头像
global.DEFAULT_AVATAR = '/static/images/avatar.png'

module.exports = {}



//主题颜色
const PRIMARY_COLOR = global.PRIMARY_COLOR || '#5D6568';

// 取消
const CANCEL_COLOR = global.CANCEL_COLOR || '#717171';


//错误提示
global.showError = function (message, onConfirm) {
  onConfirm = onConfirm || function () { }
  uni.showModal({
    title: '提示',
    content: message,
    showCancel: false,
    confirmText: '确定',
    confirmColor: PRIMARY_COLOR,
    success: onConfirm
  })
};

//提示框
global.alert = function (message) {
  uni.showModal({
    title: '提示',
    content: message,
    showCancel: false,
    confirmText: '确定',
    confirmColor: PRIMARY_COLOR
  })
};

/**
 * 确认框
 */
global.showConfirm = function (config) {
  config.confirmColor = config.confirmColor || PRIMARY_COLOR;
  config.cancelColor = config.cancelColor || CANCEL_COLOR;
  config.title = config.title || '提示'
  config.success = config.success || function(res) {
  	  if(res.confirm){
  		  config.confirm && config.confirm();
  	  }
  	  else if(res.cancel){
  		  config.cancel && config.cancel();
  	  }
  }
  
  uni.showModal(config)
}

//Toast
global.toast = function (message) {
  setTimeout(() => {
    uni.showToast({
      icon: 'none',
      title: message
    })
  }, 0)
};

// Success
global.success = function (message) {
  setTimeout(() => {
    uni.showToast({
      icon: 'success',
      title: message
    })
  }, 0)
};

// Error
global.error = function (message) {
  setTimeout(() => {
    uni.showToast({
      icon: 'none',
      title: message
    })
  }, 0)
};


//loading
global.showLoading = function (message) {

  uni.showLoading({
    title: message || ''
  });
};

//hideLoading
global.hideLoading = function () {

  uni.hideLoading();
}

/**
 *网络状态变更
 */
global.onNetworkStatusChange = function (res) {
  var status = res.isConnected;
  var currentPage = global.getCurrentPage();
  if (currentPage) {
    var components = currentPage.data.components || {};
    if (components.network) {
      currentPage.setData({
        networkStatus: status
      })
      return;
    }

    if (currentPage.onNetworkStatusChange) {
      currentPage.onNetworkStatusChange(res)
    }
  }
};

/**
 * 获取当前页面对象
 */
global.getCurrentPage = function () {
  var pages = getCurrentPages();
  var len = pages.length;
  var currentPage = null;
  if (len > 0) {
    currentPage = pages[len - 1];
  }
  return currentPage;
}

/**
 * 获取返回页面对象
 */
global.getBackPage = function (delta) {
  delta = delta || 0
  var pages = getCurrentPages();
  var len = pages.length;
  var backPage = null;
  if (len > delta + 1) {
    backPage = pages[len - 2 - delta];
  }
  return backPage;
}

// 全局回调队列
global.callbackQueue = {}
global.navigateTo = function(config){
  var callback = "onCallback" + new Date().getTime()
  global.callbackQueue[callback] = function(res){
    config.success && config.success(res);
    global.callbackQueue[callback] = null
    delete global.callbackQueue[callback]
  }
  uni.navigateTo({
    url: config.url + (config.url.indexOf('?') > 0 ? '&' : '?') + 'callback=' + callback
  })
}

/**
 * 获取当前页面组件
 */
global.getPageComponents = function () {
  var currentPage = global.getCurrentPage();
  var components = {};
  if (currentPage) {
    components = currentPage.data.components || {};
  }
  return components;
}

/**
 * 推送消息
 * @param message multi
 * @param msgType String
 */
global.push = function (body, msgType) {
  msgType = msgType || 'text'
  var data = {
    'msgtype': msgType,
    [msgType]: body
  }
  /* uni.request({
    url: global.API_BASE_PATH + '/webhook',
    method: 'POST',
    data: data
  }) */
}


/**
 * 监听错误异常
 * @param err
 * @param url
 * @param line
 */
global.onerror = function (err) {
  try {
    var message =
      '# **' + global.APP_TITLE + '**'
      + "\n\n"
      + '**Platform**：小程序'
      + "\n\n"
      + '**Error**：' + err

    var body = {
      title: '异常通知',
      text: message
    }
    global.push(body, 'markdown');
  }
  catch (e) { console.log(e) }
};

var lastLoginTime = 0;
// 调用接口登录 需要在app.js中重写
global.doLogin = (data) => { };

global.resetData = false;

//调用登录接口
global.login = () => {

  var now = new Date().getTime();
  if (now - lastLoginTime < 3000) {
    console.log('重复登录请求')
    return;
  }
  lastLoginTime = now;
  global.resetData = true;
  uni.navigateTo({
    url: '/pages/common/login'
  })
}

/**
 * 驼峰转下划线
 */
global.camel2underline = (obj) =>{
	if(typeof obj == 'string'){
		return obj.replace(/([A-Z])/g, function($1){ return "_" + $1.toLowerCase()});
	}
	
	if(obj instanceof Array){
		for(let i = 0; i < obj.length; i++){
			let v = obj[i];
			obj[i] = typeof v == 'object' ? global.camel2underline(v) : v;
		}
		return obj;
	}
	
	for(let k in obj){
		let v = obj[k];
		let unk = k.replace(/([A-Z])/g, function($1){ return "_" + $1.toLowerCase()});
		delete obj[k];
		obj[unk] = typeof v == 'object' ? global.camel2underline(v) : v;
	}
	return obj;
}


/**
 * 处理跳转事件
 */
global.handlerEvent = (event, isRedirect) => {
	
	event = global.camel2underline(event);
	if(!event.event_type || event.event_type == "nonevent"){
		return ;
	}

	var url = null;
	if(event.event_type == 'mini_program'){
		uni.navigateToMiniProgram({
			appId: event.mini_program_id,
			success(res){
				console.log(res);
			},
			fail(err){
				console.error(err);
			}
		})
		return ;
	}
	else if(event.event_type == "link"){
		url = "/pages/webview/webview?url=" + event.event_value;
	}
	else if(event.event_type == "path"){
		url= event.event_value;
	}
	if(!url){
		return ;
	}
	if(isRedirect){
		uni.redirectTo({
			url: url
		})
	}
	else{
		uni.navigateTo({
			url: url
		})
	}
}



/**
 * 钉钉推送
 */
global.dtalk = function (obj) {
  try {
    var body = {
      title: '异常通知',
      text: JSON.stringify(obj)
    }
    global.push(body, 'markdown');
  }
  catch (e) { console.log(e) }
};


/**
 * 获取权限并执行
 */
global.runWithAuth = (config) => {
  var authScope = config.scope;
  uni.getSetting({
    success: (res) => {
      var hasAuth = res.authSetting[authScope];
      // 未申请授权
      if (typeof hasAuth == 'undefined') {
        uni.authorize({
          scope: authScope,
          success() {
            config.success && config.success();
          },
          fail(err) {
            console.log(err);
          }
        })
      }
      // 拒绝授权
      else if (!hasAuth) {
        uni.openSetting({
          success: (res) => {
            if (res.authSetting[authScope]) {
              config.success && config.success();
            }
            else {
              config.fail && config.fail();
            }
          },
          fail: (err) => {
            console.log(err);
          }
        })
      }
      else {
        config.success && config.success();
      }
    },
    fail: (err) => {
      console.log(err);
    }
  });
};

class PayType{
	constructor(id, name, value) {
		this.id = id;
		this.name = name;
		this.value = value;
	}
}

global.payType = {
		alipay: new PayType(0, "支付宝", "alipay"),
		wxpay: new PayType(1, "微信支付", "wxpay"),
		coin: new PayType(2, "金币", "coin"),
		wechat: new PayType(3,"公众号支付", "wechat"),
		weapp: new PayType(4, "小程序支付", "weapp")
}

global.getWeixinPayType = global.payType.wechat;

// #ifdef APP-PLUS
global.getWeixinPayType = global.payType.wxpay;
// #endif
// #ifdef MP-WEIXIN
global.getWeixinPayType = global.payType.weapp;
// #endif

/**
 * 解析scene 数据
 */
global.parseScene = (scene)=>{
	let arr = scene.split('&');
	let map = {};
	arr.forEach(item => {
		let kv = item.split('=');
		
		let key = kv[0];
		let value = kv.splice(1).join('=');
		map[key] = value;
	});
	return map;
}


/**
 * 数组去重
 */
global.unique = function(arr, ... keys){
	if(keys.length == 0){
		keys = ['id'];
	}
	let exists = new Set();
	
	let result = arr.reduce(function(dist, item){
		
		let karr = [];
		keys.forEach(k =>{
			karr.push(item[k]);
		});
		let kstr = karr.join("#\n#");
		if(!exists.has(kstr)){
			dist.push(item);
			exists.add(kstr);
		}
		return dist;
	}, [])
	
	return result;
}


// 模型本地缓存
const CURRENT_MODEL_KEY = 'CURRENT_MODEL';
global.setModel = (model) => {
  uni.setStorageSync(CURRENT_MODEL_KEY, model);
}

global.getModel = () => {
  let value =  uni.getStorageSync(CURRENT_MODEL_KEY);
  return value || null;
}


module.exports = {}
